package com.bw.merchant.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.constants.RoutePath
import com.bw.common.view.BaseMvvmActivity
import com.bw.merchant.adapter.MerchantAdapter
import com.bw.merchant.adapter.ProfileAdapter
import com.bw.merchant.databinding.ActivityMerchantBinding
import com.bw.merchant.entity.ProfileEntity
import com.bw.merchant.net.MerchantViewModel


/**
 * 智慧园区-04-商家推荐V1.1
 * 企业档案
 * 兰宏宇
 * 20250507
 */
@Route(path = RoutePath.PATH_MERCHANT)
class MerchantActivity : BaseMvvmActivity<ActivityMerchantBinding,MerchantViewModel>() {

    private lateinit var adapter: ProfileAdapter
    private var pList:MutableList<ProfileEntity> = mutableListOf()

    override fun initView() {
        binding.ivBack.setOnClickListener { finish() }
        adapter = ProfileAdapter()
        binding.rvMerchant.adapter = adapter
        binding.rvMerchant.layoutManager = LinearLayoutManager(this)

        adapter.setOnItemClickListener { aAdapter, view, position ->
            ARouter.getInstance().build(RoutePath.PATH_MERCHANT_DETAIL)
                .withSerializable("profile",adapter.data[position])
                .navigation()
        }

        binding.tvApply.setOnClickListener {
            ARouter.getInstance().build(RoutePath.PATH_MERCHANT_SETTLED).navigation()
        }


        binding.etSearch.addTextChangedListener (object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (pList.size > 0) {
                    searchMethod(s.toString())
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })


    }

    override fun initData() {
        vm.profilesSuccess.observe(this){
            adapter.data.clear()
            adapter.data.addAll(it)
            pList.clear()
            pList.addAll(it)
            adapter.notifyDataSetChanged()
        }

    }


    override fun onResume() {
        super.onResume()
        vm.getProfiles()
    }

    fun searchMethod(searchStr: String) {

        val filter = pList.filter { profileEntity ->
            profileEntity.name.contains(searchStr) ||
                    profileEntity.industryType.contains(searchStr) ||
                    profileEntity.stockName.contains(searchStr) ||
                    profileEntity.address.contains(searchStr)
        }

        adapter.data.clear()
        adapter.data.addAll(filter)
        adapter.notifyDataSetChanged()
    }

}